# !/usr/bin/evn python3
# -*- coding: utf-8 -*-
# File Name: order.py
# Created Date: 2017-12-05 10:05:42
from app.extra import *
from .user import User
class Order(db.Model, Modelable, Serialize):
    __tablename__ = 'orders'
    __searchable__ = ['customer_name', "serial_number"]
    __analyzer__ =  ChineseAnalyzer()

    id = db.Column(db.Integer, primary_key=True)
    serial_number = db.Column(db.String, index=True, nullable=False, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    server_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    driver_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    account_id = db.Column(db.Integer, index=True)
    customer_phone = db.Column(db.String, index=True, nullable=True)
    customer_name = db.Column(db.String)
    product_type = db.Column(db.String, index=True)
    appraise = db.Column(db.Integer, default=0) #估价
    appoint_date = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()))
    remark = db.Column(db.String)
    square = db.Column(db.Float, default=0.1)
    amount = db.Column(db.Integer, default=0)
    province = db.Column(db.String)
    city = db.Column(db.String)
    district = db.Column(db.String)
    street = db.Column(db.String)
    material= db.Column(db.String)
    region = db.Column(db.String)
    order_status = db.Column(db.Integer, default=0x001)
    ship_date = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()))
    ship_status = db.Column(db.Integer, default=0x001)
    origin_addr = db.Column(db.String)
    geohash = db.Column(db.String, index=True)
    updated_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()), onupdate=time.mktime(datetime.utcnow().timetuple()))
    created_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()))

    server = db.relationship("User", foreign_keys=[server_id])
    driver = db.relationship("User", foreign_keys=[driver_id])
    user = db.relationship('User', foreign_keys=[user_id])
    pictures = db.relationship("Picture", backref="order", lazy="subquery")

    def __init__(self, **kwargs):
        super(Order, self).__init__(**kwargs)
        self.serial_number = Order.generate_number()

    def __repr__(self):
        return "<Order no:{}, user:{}, cname:{}>".format(self.serial_number, self.user_id, self.customer_name)
    
    def __str__(self):
        return "order"

    #生成订单号
    @classmethod
    def generate_number(cls,t=1, p=5):
        order = cls.query.order_by(cls.id.desc()).first()
        n = int(order.serial_number) if order else 0
        temp = str(n + t).zfill(p)
        while t < 10:
            o = Order.query.filter_by(serial_number=temp).first()
            if not o:
                return temp
            t += 1
            if t > 10:
                return temp
            if t > 4:
                p += 1
            Order.generate_number(t, p)

    

    #模糊查询订单号
    @classmethod
    def vague_orders(cls, key=None, page=1):
        temps = cls.query.filter(cls.serial_number.like("%{}%".format(key))).paginate(page, per_page=10)
        temp_page = Modelable.res_page(temps)
        return temps.items, temp_page

    #创建订单使用
    @classmethod
    def create_order(cls, **kwargs):
        try:
            order = Order(**kwargs)
            if kwargs["province"] and kwargs["city"]:
                order.geohash = order.conver_to_lat_lon()
            elif kwargs["lat"] and kwargs["lon"]:
                order.province, order.city, order.district, order.street = order.latlon_to_addr(lat=kwargs["lat"],lon=kwargs["lon"])
            db.session.add(order)
            db.session.commit()
            return True, order
        except Exception as e:
            db.session.rollback()
            print(">>>错误为: {}".format(e))
            return False, "{}".format(e)

    #修改订单, 只允许个别的修改
    def update_order(self, **kwargs):
        try:
            valid = {
                    "appraise", "city", "district", 
                    "province", "driver_id", "server_id", 
                    "customer_name", "customer_phone",
                    "remark", "product_type", "material"
                    }
            params = {k: v for k,v in kwargs.items() if k in valid and v}
            for key, value in params.items():
                setattr(self, key, value)
            db.session.add(self)
            db.session.commit()
            return True, self
        except Exception as e:
            db.session.rollback()
            return False, "{}".format(e)

        
 
    #生成假数据
    @staticmethod
    def generate_fake_user(count=100):
        from random import seed, randint
        import forgery_py
        seed()
        u_count = User.query.count()
        temps = [
                (31.222, 121.345), 
                (30.111, 121.645), 
                (31.567, 120.345),
                (31.234, 121.845),
                (31.734, 121.111)
                ]

        for i in range(count):
            t = User.query.filter(User.accounts).all()
            u = t[randint(0, len(t) - 1)]
            g = geohash.encode(*temps[randint(0, len(temps) -1)])
            o = Order(customer_name=forgery_py.name.full_name(), customer_phone=forgery_py.address.phone(), user=u, account_id=u.accounts[randint(0, len(u.accounts) -1)].id, geohash=g)
            db.session.add(o)
            try:
                db.session.commit()
            except Exception as e:
                print("错误{}".format(e))
                db.session.rollback()

whooshalchemy.whoosh_index(app, Order)
    


        


